﻿using System;
using System.Collections.Generic;
using SpiderPlatform.Common;
using System.Text.RegularExpressions;
using SpiderPlatform.Entity;
using SpiderPlatform.Dao;
using Newtonsoft.Json;
using System.Linq;
using Yamibuy.Framework.Core.Tools;
using System.Net;

namespace SpiderPlatform.Service
{
    public class YamibuyService
    {

        ItemDao dao = new ItemDao();
        public void doWork()
        {

            //var itemlist = dao.QueryChannelItem(1);
            var listUrl = "https://m.yamibuy.com/api/search/searchResultsNew";
            var itemUrl = "https://m.yamibuy.com/item/";
            int pageIndex = 1;
            string upData = string.Empty;
            var token = Guid.NewGuid().ToString();
            YamibuyListResult ymList = new YamibuyListResult(); 
            do
            {
                Logger.Info($"开始导入第{pageIndex}页");
                upData = JsonConvert.SerializeObject(new
                {
                    pageIndex = pageIndex,
                    page_size = 100,
                    exclude_cat_id = "11",
                    input = "",
                    cat_id = "",
                    seller_ids = "",
                    tags = "",
                    price_min = "",
                    price_max = "",
                    is_yami = 0,
                    is_declare = 0,
                    is_uk = 0,
                    is_promote = 0,
                    is_instock = 0,
                    sort_by = 3,
                    sort_order = 0,
                    ps_ids = ""
                });
                var result = HttpHelper.PostUrl(listUrl, upData, token);
                result = Regex.Unescape(result);
                result = JsonHelper.JsonReplaceSign(result);
                List<ChannelItemHistoryEntity> hisList = new List<ChannelItemHistoryEntity>();             
                try
                {                 
                    ymList = JsonConvert.DeserializeObject<YamibuyListResult>(result);
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.Message);
                    Logger.Info("数据非法，本次商品忽略");
                    pageIndex++;
                    continue;
                }
                if (ymList.data.items.Length > 0)
                {
                    foreach (var item in ymList.data.items)
                    {                      
                        hisList.Add(new ChannelItemHistoryEntity
                        {
                            channel_id = 1,
                            channel_sku = item.item_number,
                            score = item.rated,
                            is_instock = item.goods_number,
                            reviews = item.comment_count,
                            price = item.shop_price,
                            title = item.goods_name,
                            link = itemUrl + item.item_number,
                            images = "http://cdn.yamibuy.net/"+item.image_url                                    
                        });
                    }
                }
                Logger.Info($"开始导入商品信息...，共{hisList.Count}条");
                if (hisList.Count==0)
                {
                    break;
                }
                hisList = hisList.Distinct(new ChannelItemHistoryComparer()).ToList();
                dao.CreateChannelItemHistory(hisList);

                var hisExists = dao.QueryChannelItemBySku(1, hisList.Select(p=>p.channel_sku).ToList());                

                //检查是否有新的商品出现
                var diffList = hisList.Except(hisExists, new ChannelItemHistoryComparer());
                //记录新的item   
                var newItemList = diffList.ToList().ToTypeList<ChannelItemHistoryEntity, ChannelItemEntity>();
                Logger.Info($"检查新商品...，共{newItemList.Count}条");
                if (newItemList.Count > 0)
                {
                    Logger.Info($"导入新商品step1...");
                    dao.CreateChannelItem(newItemList);
                    var realList = diffList.ToList();
                    Logger.Info($"导入新商品step2...");
                    dao.CreateChannelItemRealTime(realList);             
                }
                Logger.Info($"更新商品信息...");
                dao.UpdateChannelItemRealTime(hisList);
                pageIndex++;
                Logger.Info($"===================本次请求完成======================");
            } while (ymList.data.items.Count()>0);            

            Logger.Info("任务完成");            
        }
    }
}
